<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="客户名称" v-if="permissionStore.hasPermisson('ppzl.cx')">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.dropDownData"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar
            class="gesture"
            :items="pageData.btnList"
            @add="addHandler"
            @del="deleteHandler"
            @select="selectHandler"
            @export="exports"
            @import="importHandler"
            @excel="downloadHandler"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :ok-loading="pageData.pageLoading"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="120px"
            label="编号"
            field="brandCode"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="" v-model="dataForm.brandCode" disabled />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="客户名称"
            field="brandName"
            :rules="[{ required: true, message: '客户名称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="" v-model="dataForm.brandName" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="所属公司"
            field="companyName"
            :validate-trigger="['change', 'blur']"
          >
            <a-cascader
              v-model="dataForm.companyName"
              :field-names="companyNames"
              :options="pageData.companyList"
              allow-clear
              ref="casOb"
              class="bacClass"
              popup-container="html"
            />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="客户分类"
            field="brandType"
            :rules="[{ required: true, message: '客户分类必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              :loading="loading"
              placeholder="请选择客户分类"
              v-model="dataForm.brandType"
              @change="brandTypeChange"
              allow-clear
            >
              <a-option
                :style="{ width: '270px' }"
                v-for="item in pageData.brandTypeList"
                :value="item.detailName"
                >{{ item.detailName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="客户分组"
            field="brandClass"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              :loading="loading"
              placeholder="请选择客户分组"
              v-model="dataForm.brandClass"
              allow-clear
            >
              <a-option
                :style="{ width: '270px' }"
                v-for="item in pageData.brandClassList"
                :value="item.detailName"
                >{{ item.detailName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="联系方式"
            field="telephone"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="请填写联系方式" v-model="dataForm.telephone" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="联系人"
            field="contactPerson"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="请填写联系人" v-model="dataForm.contactPerson" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="开户银行"
            field="openBank"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="请填写开户银行" v-model="dataForm.openBank" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="户名"
            field="bankName"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="请填写户名" v-model="dataForm.bankName" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="银行账号"
            field="bankNumber"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="请填写银行账号" v-model="dataForm.bankNumber" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="品牌"
            field="makeName"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="请填写品牌" v-model="dataForm.makeName" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="ERRID"
            field="erpId"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="请填写ERRID" v-model="dataForm.erpId" />
          </a-form-item>
          <a-form-item
            label-col-flex="120px"
            label="验布保留小数位"
            field="decimalNum"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              :loading="loading"
              v-model="dataForm.decimalNum"
              allow-clear
            >
              <a-option value="1" style="width: 150px">1位</a-option>
              <a-option value="2" style="width: 150px">2位</a-option>
              <a-option value="3" style="width: 150px">3位</a-option>
              <a-option value="4" style="width: 150px">4位</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="120px" label="备注" field="remark">
            <a-textarea
              class="bacClass"
              placeholder=""
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Button, Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import MyTable from '@/components/MyTable'
  import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
  import { template } from 'lodash'
  import { setupGlobalComponent } from '@/layouts'
  import { pagingList } from '@/api/paging'
  // 引入
  
  import { localeText } from '@/api/aggridZw'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  import { DEFAULT_FORMATS_DATEPICKER } from 'element-plus'

  interface BrandInfo {
    id: any
    brandCode: string
    brandName: string
    clothClass: string
    remark: string
    deleteState: number | string
    createName: string
    createTime: string
    updateName: string
    updateTime: string
    companyId: any
    brandType: any
    telephone: any
    contactPerson: any
    openBank: any
    bankName: any
    bankNumber: any
    makeName: any
    erpId: any
    brandClass: any
    companyName: any
    decimalNum: any
  }

  export default {
    name: 'BrandInfo',

    setup() {
      let cxbl = ''
      //查询
      const selectHandler = () => {
        page.value = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const table1Ref = ref<any>(null)
      const tableColumns = [
        {
          title: '编号',
          key: 'brandCode',
          dataIndex: 'brandCode',
          width: 150,
        },

        {
          title: '客户名称',
          key: 'brandName',
          dataIndex: 'brandName',
          width: 150,
        },
        // {
        //     title: "布类类型",
        //     key: "clothClass",
        //     dataIndex: "clothClass",
        //     width: 150
        // },
        {
          title: '所属公司',
          key: 'companyName',
          dataIndex: 'companyName',
          width: 150,
        },
        {
          title: '客户分类',
          key: 'brandType',
          dataIndex: 'brandType',
          width: 150,
        },
        {
          title: '序号',
          key: 'serialNo',
          dataIndex: 'serialNo',
          width: 150,
        },
        {
          title: '联系方式',
          key: 'telephone',
          dataIndex: 'telephone',
          width: 150,
        },
        {
          title: '联系人',
          key: 'contactPerson',
          dataIndex: 'contactPerson',
          width: 150,
        },
        {
          title: '开户银行',
          key: 'openBank',
          dataIndex: 'openBank',
          width: 150,
        },
        {
          title: '验布保留小数位',
          key: 'decimalNum',
          dataIndex: 'decimalNum',
          slotName: 'decimalNum',
          width: 150,
        },
        {
          title: '户名',
          key: 'bankName',
          dataIndex: 'bankName',
          width: 150,
        },
        {
          title: '银行账号',
          key: 'bankNumber',
          dataIndex: 'bankNumber',
          width: 150,
        },
        {
          title: '品牌',
          key: 'makeName',
          dataIndex: 'makeName',
          width: 150,
        },
        {
          title: 'ERRID',
          key: 'erpId',
          dataIndex: 'erpId',
          width: 150,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        // {
        //     title: "删除状态",
        //     key: "deleteState",
        //     dataIndex: "deleteState",
        //     width: 100,
        //     slotName: "deleteState",
        //     fixed: 'right'
        // },
        {
          title: '操作',
          key: 'id',
          slotName: 'act',
          width: 150,
          fixed: 'right',
        },
      ]
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        obj['width'] = '250px'
        if (o.slotName === 'act') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 90
          obj['cellRenderer'] = {
            template: `
            <a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                e: pageData.isEdit,
                a,
              }
            },
          }
        }
        if (o.slotName === 'decimalNum') {
          obj['valueGetter'] = (params: any) => {
            return params.data.decimalNum == 1
              ? '1位'
              : params.data.decimalNum == 2
              ? '2位'
              : params.data.decimalNum == 3
              ? '3位'
              : params.data.decimalNum == 4
              ? '4位'
              : ''
          }
        }
        return obj
      })
      // tc.unshift(
      // {
      //     headerName: '行号',
      //     pinned: 'left',
      //     resizable: false,
      //     filter: false,
      //     sortable: false,
      //     width: 50,
      //     valueGetter: function (params) {
      //       return params.node ? params.node.rowIndex + 1 : null;
      //     }
      //   },
      // )
      tc.unshift({
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      })
      let configTable1 = {
        url: 'product/Brand/getPage', //接口路径
        queryData: {
          //接口参数
          deleteState: '0',
          brandName: cxbl,
        },
        paginationShow: true, //分页是否显示
        invokeiIterface: true, //是否调用接
        rowMultiSelectWithClick: true, //点击行是否多选
        column: tc,
        fileName: 'Categoriesofyarncount',
      }

      const total = ref(0)
      const page = ref(1)
      const size = ref(10)

      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }

      function change1(val: any) {
        size.value = val
        doRefresh()
      }

      const headerShow = ref<boolean>(true)
      const companyNames = { value: 'label', label: 'label' }

      function doRefresh() {
        table1Ref.value.setQuery({
          deleteState: '0',
          brandName: cxbl,
        })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        nameList: []
        pageLoading: boolean
        typeList: []
        dropDownData1: any
        rHeight: any
        btnList: any[]
        isEdit: boolean
        companyList: []
        brandTypeList: any[]
        brandClassList: any[]
      }>({
        nameList: [],
        showAdd: false,
        sideTitle: '新增品牌资料',
        dropDownData: '',
        pageLoading: false,
        typeList: [],
        dropDownData1: '',
        rHeight: 0,
        btnList: [],
        isEdit: false,
        companyList: [],
        brandTypeList: [],
        brandClassList: [],
      })

      interface gcType {
        id: any
        company: any
      }

      //下拉框得到焦点
      const focusSel = () => {
        selCxAll({ brandName: '', deleteState: 0 })
      }
      //下拉数据
      const options = ref<any>(pageData.nameList)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { brandName: value, deleteState: 0 }
          loading.value = true
          selCxAll(ob)
          options.value = pageData.nameList
          loading.value = false
        } else {
          options.value = []
        }
      }

      //下拉框查询
      function selCxAll(val: any) {
        post({
          url: 'product/Brand/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            let dataList: any = []
            data.forEach(function (o: any) {
              dataList.push(o['brandName'])
            })
            pageData.nameList = dataList
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      onMounted(() => {
        // 切换tap到本页面执行的方法
        emitter.on('BrandInfo', () => {
          // selCxAll1({});
          doRefresh()
        })
      })
      const queryData = reactive({
        clothType: '',
      })
      //获取客户分类
      const getBrandTypeList = async () => {
        try {
          const res = await post({
            url: 'dict/dictTypeDetail/getList',
            data: { codeType: 47 },
          })
          if (res.code == 200) {
            pageData.brandTypeList = res.data.map((item: any) => {
              return {
                detailName: item.detailName,
                detailCode: item.detailCode,
              }
            })
          } else {
            Message.error({
              content: res.message,
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
      const getCompanyList = async () => {
        try {
          const res = await post({
            url: 'org/baCompany/getTreeCompanyByUser',
          })
          if (res.code == 200) {
            pageData.companyList = res.data
          } else {
            Message.error({
              content: res.message,
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
      const brandTypeChange = async (e: any) => {
        const detailCode = pageData.brandTypeList.find(
          (item: any) => item.detailName === e
        ).detailCode
        try {
          const res = await post({
            url: 'product/Brand/getCodeGenerate',
            data: { brandTypeCode: detailCode },
          })
          if (res.code == 200) {
            dataForm.brandCode = res.data
          } else {
            Message.error({
              content: res.message,
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
      //获取客户分组
      const getBrandClassList = async () => {
        try {
          const res = await post({
            url: 'dict/dictTypeDetail/getList',
            data: { codeType: 48 },
          })
          if (res.code == 200) {
            pageData.brandClassList = res.data.map((item: any) => {
              return {
                detailName: item.detailName,
              }
            })
          } else {
            Message.error({
              content: res.message,
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
      const addHandler = () => {
        getCompanyList()
        getBrandTypeList()
        getBrandClassList()
        // selCxAll1({ clothClass: '' })
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else {
            dataForm[key] = ''
          }
        }

        pageData.showAdd = true
        pageData.sideTitle = '新增品牌资料'
      }
      const dataForm = reactive<BrandInfo>({
        id: null,
        remark: '',
        brandName: '',
        clothClass: '',
        deleteState: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        brandCode: '',
        companyId: '', //公司id
        brandType: '', //客户分类
        telephone: '',
        contactPerson: '',
        openBank: '',
        bankName: '',
        bankNumber: '',
        makeName: '',
        erpId: '',
        brandClass: '',
        companyName: '',
        decimalNum: '',
      })

      // 表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }

      let formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            formRef.value?.validate().then((err) => {
              if (!err) {
                pageData.pageLoading = true
                if (pageData.sideTitle === '新增品牌资料') {
                  post({
                    url: 'product/Brand/insert',
                    data: [dataForm],
                  })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false

                        Message.success({
                          content: '新增成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                      doRefresh()
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
                } else {
                  post({
                    url: 'product/Brand/update',
                    data: [dataForm],
                  })
                    .then((res: any) => {
                      if (res.code === 200) {
                        formRef.value?.resetFields()
                        pageData.showAdd = false
                        Message.success({
                          content: '修改成功',
                          duration: 5000,
                        })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                    })
                    .finally(() => {
                      doRefresh()
                      pageData.pageLoading = false
                    })
                }
              }
            })
          }
        })
      }
      const deleteHandler = () => {
        if (table1Ref.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }

        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              url: 'product/Brand/deleteList',
              data: table1Ref.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '删除失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }
      const renderEditData = async (id: any) => {
        try {
          const res = await post({
            url: 'product/Brand/getList',
            data: { id },
          })
          if (res.code == 200) {
            dataForm['brandCode'] = res.data[0].brandCode
            dataForm['brandName'] = res.data[0].brandName
            dataForm['companyName'] = res.data[0].companyName
            dataForm['brandType'] = res.data[0].brandType
            dataForm['brandClass'] = res.data[0].brandClass
            dataForm['telephone'] = res.data[0].telephone
            dataForm['contactPerson'] = res.data[0].contactPerson
            dataForm['openBank'] = res.data[0].openBank
            dataForm['bankName'] = res.data[0].bankName
            dataForm['bankNumber'] = res.data[0].bankNumber
            dataForm['makeName'] = res.data[0].makeName
            dataForm['erpId'] = res.data[0].erpId
            dataForm['remark'] = res.data[0].remark
          } else {
            Message.error({
              content: res.message,
            })
          }
        } catch (error) {
          console.log(error)
        }
      }
      let curobj = null
      const editHandler = (record: BrandInfo) => {
        getCompanyList()
        getBrandTypeList()
        getBrandClassList()
        curobj = record
        renderEditData(record.id)
        // selCxAll1({ key: '' })
        // dataForm.brandCode = record.brandCode
        dataForm.brandName = record.brandName
        dataForm.clothClass = record.clothClass
        dataForm.remark = record.remark
        dataForm.id = record.id
        pageData.sideTitle = '修改品牌资料'
        pageData.showAdd = true
      }
      //判断是否填写了中文
      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      //导出
      const exports = () => {
        if (table1Ref.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        } else {
          let idList: any = []
          table1Ref.value.getSelectedRows().forEach(function (o: any) {
            idList.push(o['id'])
          })
          //将表头拼接出来
          let head =
            '<th>编号</th><th>客户名称</th><th>所属公司</th><th>客户分类</th><th>序号</th><th>联系方式</th><th>联系人</th><th>开户银行</th><th>户名</th><th>银行账号</th><th>品牌</th><th>ERRID</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
          //拿到当前表格数据与勾选的行做筛选

          let nowRow = table.dataList.filter(function (o) {
            return (
              gridOption.value
                .getSelectedRows()
                .map((o: any) => {
                  return o.id
                })
                .indexOf(o['id']) !== -1
            )
          })
          let body = ''
          nowRow.forEach(function (o) {
            body += '<tr><td>' + o['brandCode'] + '</td>'
            body += '<td>' + o['brandName'] + '</td>'
            body += '<td>' + o['companyName'] + '</td>'
            body += '<td>' + o['brandType'] + '</td>'
            body += '<td>' + o['serialNo'] + '</td>'
            body += '<td>' + o['telephone'] + '</td>'
            body += '<td>' + o['contactPerson'] + '</td>'
            body += '<td>' + o['openBank'] + '</td>'
            body += '<td>' + o['bankName'] + '</td>'
            body += '<td>' + o['bankNumber'] + '</td>'
            body += '<td>' + o['makeName'] + '</td>'
            body += '<td>' + o['erpId'] + '</td>'
            body += '<td>' + o['remark'] + '</td>'
            body += '<td>' + o['createName'] + '</td>'
            body += '<td>' + o['createTime'] + '</td>'
            body += '<td>' + o['updateName'] + '</td>'
            body += '<td>' + o['updateTime'] + '</td>'
            body += '</tr>'
          })
          tableToXlsx(head, '客户资料', body)
          console.log(table)
        }
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
              <head><meta charset="UTF-8"></head>
              <body><table border="1"><tr>${head}</tr>${body}</table></body>
          </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }

      //模板下载
      const downloadHandler = () => {
        axios
          .get(baseURL + '/product/Brand/uploadModel', {
            responseType: 'blob',
            headers: {
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((res) => {
            if (res.status === 200) {
              filedownload(res.data, '客户资料.xlsx')
            }
          })
      }
      //导入
      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          pageData.pageLoading = true
          axios
            .post(baseURL + '/product/Brand/importModelData', formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((result) => {
              if (result.data['code'] === 200) {
                Message.success('导入成功')
              } else {
                Message.error(result.data.message)
              }
            })
            .finally(() => {
              pageData.pageLoading = false
              doRefresh()
            })
        })
        inputEle.click()
      }
      //下拉数据
      const options1 = ref<any>(pageData.typeList)
      const loading1 = ref(false)
      const handleSearch1 = (value: any) => {
        if (value) {
          const ob = {
            key: value,
            deleteState: 0,
          }
          loading.value = true
          selCxAll1(ob)
          options.value = pageData.typeList
          loading.value = false
        } else {
          options.value = []
        }
      }
      //下拉框得到焦点
      const focusSel1 = () => {
        selCxAll1({ key: '' })
      }
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

      if (permissionStore.hasPermisson('ppzl.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('ppzl.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('ppzl.sc')) {
        pageData.btnList.push('删除')
      }
      if (permissionStore.hasPermisson('ppzl.dc')) {
        pageData.btnList.push('导出')
      }
      if (permissionStore.hasPermisson('ppzl.dr')) {
        pageData.btnList.push('导入')
      }
      if (permissionStore.hasPermisson('ppzl.mbxz')) {
        pageData.btnList.push('模板下载')
      }
      if (permissionStore.hasPermisson('ppzl.xg')) {
        pageData.isEdit = true
      }

      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      const huiche = () => {
        page.value = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const pagingList1: any = ref(pagingList)
      const localeText1: any = ref(localeText)
      return {
        colState,
        pagingList1,
        huiche,
        localeText1,
        defaultColDef,
        tc,
        total,
        PageSize,
        change1,
        page,
        size,
        editHandler,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        selectHandler,
        isChiese,
        // inputBlur,
        exports,
        options,
        loading,
        handleSearch,
        focusSel,
        downloadHandler,
        importHandler,
        options1,
        loading1,
        handleSearch1,
        focusSel1,
        headerShow,
        handleChange,
        gridReady,
        permissionStore,
        getBrandClassList,
        getBrandTypeList,
        brandTypeChange,
        companyNames,
        table1Ref,
        configTable1,
      }
    },
    components: { Toolbar, PageTabelLayout,  },
  }
</script>
